package tron.oauth.config;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import java.util.Collection;
import java.util.List;

public class CustomerFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {


    private final RootService rootService;

    public CustomerFilterInvocationSecurityMetadataSource(RootService rootService) {
        this.rootService = rootService;
    }


    /**
     * 通过当前请求的URL获取角色信息
     * @param o(FilterInvocation) 用于获取当前请求的url
     * @return 当前请求url所需的角色
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 在这个环节可以判断请求是否具有token，并判断token有效性
        FilterInvocation filterInvocation = (FilterInvocation) o;
        String url = filterInvocation.getRequestUrl();
        System.out.printf("-------------------拦截到请求: %s，返回当前资源所需要的权限---------------------%n",url);
        rootService.getRoleByUrl();
        final List<ConfigAttribute> list = SecurityConfig.createList("ROLE_ANONYMOUS");
        return list;
    }

    /**
     * 返回所有定义好的权限资源
     * Spring Security在启动时会校验相关配置是否正确，如果不需要校验，直接返回null
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 是否支持校验
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
